package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName :  RecommendUserInfoService
 * @Author : Tenebrous
 * @Date: 2020/12/11 14:06
 * @Description : 推荐朋友业务层
 */
@Service
public class RecommendUserInfoService {

    @Autowired
    private UserService userService;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private UserInfoService userInfoService;

    @Value("${tanhua.sso.default.recommend.users}")
    private String defaultRecommendUsers;

    /**
     * 查询推荐用户信息
     * @param queryParam    推荐用户查询的条件
     * @param token         用户登录时携带的token
                * @return              返回最终推荐用户的信息
                */
        public PageResult queryRecommendUserList(RecommendUserQueryParam queryParam, String token) {
            // 根据token查询当前登录的用户信息
            User user = userService.queryUserByToken(token);
            if (null == user) {
                // 如果为null,返回null
                return null;
            }
            // 查询推荐用户信息，参数为登录者id，分页参数
            PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(), queryParam.getPage(), queryParam.getPageSize());
            List<RecommendUser> records = pageInfo.getRecords();

            // 如果未查询到，需要使用默认推荐列表
            if(CollectionUtils.isEmpty(records)) {
                String[] ss = StringUtils.split(defaultRecommendUsers, ',');

                for (String s : ss) {
                    RecommendUser recommendUser = new RecommendUser();
                    recommendUser.setUserId(Long.valueOf(s));
                    recommendUser.setToUserId(user.getId());
                    recommendUser.setScore(RandomUtils.nextDouble(70, 98));
                    records.add(recommendUser);
                }
            }

            // 需要查询用户的信息，并且按照条件查询
            List<Long> userIds = new ArrayList<>();
            for (RecommendUser record : records) {
                userIds.add(record.getUserId());
            }
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        // 用户id
        queryWrapper.in("user_id", userIds);

/*        if (StringUtils.isNotEmpty(queryParam.getGender())) {
            if ("man".equals(queryParam.getGender())) {
                queryWrapper.eq("sex", 1);
            } else {
                queryWrapper.eq("sex", 2);
            }
        }*/

      /*  if(queryParam.getAge() != null) {
            // 年龄
            queryWrapper.lt("age", queryParam.getAge());
        }
        if(StringUtils.isNotEmpty(queryParam.getCity())) {
            // 城市
            queryWrapper.eq("city", queryParam.getCity());
        }
*/
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            // 设置头像
            todayBest.setAvatar(userInfo.getLogo());
            // 设置性别 (.name的原因是mock文档中需要的是men和women，而且为小写，枚举中的为大写，需要转换)
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            // 设置标签(多个信息，需要用‘,’分割)
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            // 设置缘分值
            for (RecommendUser record : records) {
                if (record.getUserId().longValue() == todayBest.getId().longValue()) {
                    double score = Math.floor(record.getScore());
                    todayBest.setFateValue(Double.valueOf(score).longValue());
                }
            }
            todayBests.add(todayBest);

            // 对结果集做排序，按照缘分值进行排序
            todayBests.sort((o1, o2)
                    ->
                    Long.valueOf(o2.getFateValue() - o1.getFateValue()).intValue());
        }
        return new PageResult(0, queryParam.getPageSize(), 0, queryParam.getPage(), todayBests);
    }

}
